package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;
    @Override
    public Cart add(Cart cart) {
        //判断当前添加的菜品或者套餐是否在数据表中已存在
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId())
                .eq(cart.getDishId() != null,Cart::getDishId,cart.getDishId())
                .eq(cart.getSetmealId() != null,Cart::getSetmealId,cart.getSetmealId());
        Cart cartFromDB = cartMapper.selectOne(wrapper);
        if (cartFromDB != null){
            //在数据库中已经存在,只要将number+1,更新回数据库
            cartFromDB.setNumber(cartFromDB.getNumber()+1);
            cartMapper.updateById(cartFromDB);
            return cartFromDB;
        }else {
            //在数据库中不存在,需要新建一个cart,保存到库中
            cart.setUserId(UserHolder.get().getId());
            cart.setNumber(1);
            cart.setCreateTime(new Date());
            cartMapper.insert(cart);
            return cart;
        }
    }

    //查询购物车
    @Override
    public List<Cart> findList() {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,UserHolder.get().getId());
        return cartMapper.selectList(wrapper);
    }

    //修改购物车
    @Override
    public Cart sub(Cart cart) {
        return null;
    }
    //清空购物车
    @Override
    public void clean() {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,UserHolder.get().getId());
        cartMapper.delete(wrapper);
    }
}
